<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-container" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
        <el-form-item label="账号">
          <el-input
            v-model="queryParams.account"
            placeholder="请输入账号"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-input
            v-model="queryParams.operation"
            placeholder="请输入操作类型"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8 mt20">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
          >清空</el-button
        >
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="logList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="80"
          :index="indexMethod"
        />
        <el-table-column
          label="账号"
          align="center"
          prop="account"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作描述"
          align="center"
          prop="operation"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="请求方法"
          align="center"
          prop="method"
          width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="请求参数"
          align="center"
          prop="params"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleViewParams(scope.row)"
              v-if="scope.row.params"
              >查看</el-button
            >
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" align="center" prop="ip" width="130" />
        <el-table-column
          label="操作时间"
          align="center"
          prop="createTime"
          width="180"
          sortable
        />
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteSingle(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>

    <!-- 参数详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <pre class="params-pre">{{ paramsContent }}</pre>
    </el-dialog>
  </div>
</template>

<script>
import { getLogList, deleteLog, clearLogs } from "@/api/log";

export default {
  name: "OperationLog",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 日志表格数据
      logList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 参数内容
      paramsContent: "",
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        account: undefined,
        operation: undefined,
        startTime: undefined,
        endTime: undefined,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询日志列表 */
    getList() {
      this.loading = true;

      // 处理日期范围
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = undefined;
        this.queryParams.endTime = undefined;
      }

      getLogList(this.queryParams)
        .then((response) => {
          if (response.code === 200) {
            this.logList = response.data.records;
            this.total = response.data.total;
          } else {
            this.$message.error(response.msg || "获取日志列表失败");
            this.logList = [];
            this.total = 0;
          }
        })
        .catch((error) => {
          console.error("获取日志列表出错:", error);
          this.$message.error("获取日志列表出错");
          this.logList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 表格序号 */
    indexMethod(index) {
      return (
        (this.queryParams.pageNo - 1) * this.queryParams.pageSize + index + 1
      );
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        account: undefined,
        operation: undefined,
        startTime: undefined,
        endTime: undefined,
      };
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 查看参数详情 */
    handleViewParams(row) {
      this.open = true;
      this.title = "参数详情";

      try {
        // 尝试格式化JSON
        const obj = JSON.parse(row.params);
        this.paramsContent = JSON.stringify(obj, null, 4);
      } catch (e) {
        // 如果不是JSON则直接显示
        this.paramsContent = row.params;
      }
    },

    /** 删除单条记录 */
    handleDeleteSingle(row) {
      this.$confirm("是否确认删除该条日志记录?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteLog([row.id]);
        })
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(response.msg || "删除失败");
          }
        })
        .catch(() => {});
    },

    /** 批量删除按钮操作 */
    handleDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }

      this.$confirm(
        `是否确认删除选中的 ${this.ids.length} 条日志记录?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return deleteLog(this.ids);
        })
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(response.msg || "删除失败");
          }
        })
        .catch(() => {});
    },

    /** 清空按钮操作 */
    handleClear() {
      this.$confirm("是否确认清空所有日志记录? 此操作不可恢复!", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return clearLogs();
        })
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("清空成功");
            this.getList();
          } else {
            this.$message.error(response.msg || "清空失败");
          }
        })
        .catch(() => {});
    },

    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    /** 分页页码改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNo = val;
      this.getList();
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 10px;
}

.mb8 {
  margin-bottom: 8px;
}

.mt20 {
  margin-top: 20px;
}

.params-pre {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  padding: 12px;
  border-radius: 4px;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
  max-height: 400px;
  overflow-y: auto;
  word-break: break-all;
  white-space: pre-wrap;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>